<template>
  <a-modal
    v-model:open="visible"
    centered
    :title="modalTitle"
    width="600px"
    :confirm-loading="confirmLoading"
    @ok="onSubmit"
    @cancel="onClose"
  >
    <a-form ref="formRef" :model="formState" layout="vertical" name="teacherForm" autocomplete="off" :rules="rules">
      <a-form-item label="学生姓名" name="username">
        <a-input v-model:value="formState.username" :maxlength="50" placeholder="请输入学生姓名" />
      </a-form-item>

      <div class="flex gap-x-24">
        <a-form-item class="flex-1" label="学号" name="number">
          <a-input v-model:value="formState.number" :maxlength="20" placeholder="请输入学号" />
        </a-form-item>
        <a-form-item class="flex-1" label="手机号码" name="tel">
          <a-input v-model:value="formState.tel" :maxlength="11" placeholder="请输入手机号码" />
        </a-form-item>
      </div>

      <a-form-item label="所属班级" name="orgId">
        <a-tree-select
          v-model:value="formState.orgId"
          :loading="organizationOptionsLoading"
          tree-default-expand-all
          :tree-data="treeData"
          placeholder="请选择班级"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
  import type { Rule } from 'ant-design-vue/es/form'
  import { TreeSelectProps } from 'ant-design-vue/es/tree-select'
  import { regex } from 'g6-fn'
  import { reactive, ref, watch } from 'vue'
  import { useRequest } from 'vue-request'

  import { useModalForm } from '@/hooks/use-modal-form'
  import { teacherManageApi } from '@/services/api/aigc-admin'

  interface FormState {
    username?: string
    number?: string
    tel?: string
    orgId?: string
  }

  const emits = defineEmits<{
    (e: 'submit', state: FormState): void
    (e: 'close'): void
  }>()

  const rules: Record<string, Rule[]> = {
    username: [
      { required: true, message: '请输入学生姓名', trigger: 'change' },
      {
        pattern: /^[\u4e00-\u9fa5a-zA-Z]{1,20}$/,
        message: '请输入正确的学生姓名'
      }
    ],
    number: [
      { required: true, message: '请输入学号', trigger: 'change' },
      {
        pattern: /^[A-Za-z0-9]{1,20}$/,
        message: '请输入正确的学号'
      }
    ],
    tel: [
      { required: false, message: '请输入手机号', trigger: 'change' },
      { pattern: regex.phone, message: '请输入正确的手机号' }
    ],
    orgId: [{ required: true, message: '请选择所属班级', trigger: 'change' }]
  }

  const formState = reactive<FormState>({
    username: '',
    number: '',
    tel: '',
    orgId: undefined
  })

  const { formRef, visible, modalTitle, confirmLoading, open, close, setFormState, resetForm, changeConfirmLoading } =
    useModalForm(formState)

  const treeData = ref<TreeSelectProps['treeData']>([])
  const { loading: organizationOptionsLoading, refresh } = useRequest<any>(teacherManageApi.getOrganizationTree, {
    onSuccess({ data }) {
      const deep = (data: any[]): any[] | null => {
        if (!data) {
          return null
        }
        return data.map((item: any) => {
          return {
            label: item.orgName,
            value: item.id,
            disabled: !(item.isAuthActive && item.level === 5),
            children: deep(item.children)
          }
        })
      }
      treeData.value = deep(data) || []
    }
  })

  watch(
    () => visible.value,
    val => {
      if (val) {
        refresh()
      }
    }
  )

  const onClose = () => {
    close()
    emits('close')
  }

  const onSubmit = async () => {
    await formRef.value?.validate()
    emits('submit', formState)
  }

  defineExpose({
    open,
    close,
    modalTitle,
    setFormState,
    resetForm,
    changeConfirmLoading
  })
</script>
